﻿//访问接口参考：https://lbs.amap.com/api/webservice/guide/api/weatherinfo

var http = require('http');
var request = require('sync-request');
var url = require('url');
var util = require('util');
 

function getCityByLL(location) {
    var keyLocation = "3cc3f3265b5e6371caf08f9188f88dbc"; //逆地理编码
    var urlLocation = "https://restapi.amap.com/v3/geocode/regeo?";
    urlLocation = urlLocation + "location=" + location + "&key=" + keyLocation;
    console.log(urlLocation);
    try {
        var res = request('GET', encodeURI(urlLocation));
        //解析城市
        console.log(res.getBody().toString());
        var obj = JSON.parse(res.getBody().toString());

        if(obj.status == '1' && obj.regeocode != null){
            var city = obj.regeocode.addressComponent.city;
            var province = obj.regeocode.addressComponent.province;
            console.log(city);
            console.log(province);
            if(typeof(city) == "string"){
                return city;
            }
            if(typeof(province) == "string"){
                return province;
            }
            /*for (var k in city) {
                if (city[k] instanceof Object) {
                    console.log(city[k]);
                    return city[k];
                }
            }*/
        }
    }
    catch (err) {
        console.log(err);
    }
    return "";
}

function getCity(wIP) {
    var keyIPLocation = "3cc3f3265b5e6371caf08f9188f88dbc"; //IP定位接口
    //var urlIPLocation = "https://restapi.amap.com/v5/ip?";
    //urlIPLocation = urlIPLocation + "type=4&ip=" + wIP + "&key=" + keyIPLocation;
    var urlIPLocation = "https://restapi.amap.com/v3/ip?";
    urlIPLocation = urlIPLocation + "ip=" + wIP + "&key=" + keyIPLocation;
    console.log(urlIPLocation);
    try {
        var res = request('GET', encodeURI(urlIPLocation));
        //解析城市
        var citycode = "";
        var json = JSON.parse(res.getBody().toString());
        //console.log(json);
        if (json.status == '1' && json.city != null) {
            //var district = json.district;
            return json.city;
        }
        else if (json.status == '1' && json.location != null) {
            return getCityByLL(json.location);
        }
    }
    catch (err) {
        console.log(err);
    }
    return "";
}

function getCitycode(city) {
    //查询行政区域编号
    var keyDistrict = "3cc3f3265b5e6371caf08f9188f88dbc";
    var urlDistrict = "https://restapi.amap.com/v3/config/district?";
    urlDistrict = urlDistrict + "keywords=" + city + "&key=" + keyDistrict;
    console.log(urlDistrict);
    try {
        var res = request('GET', encodeURI(urlDistrict));

        //解析区域编号
        var json = JSON.parse(res.getBody().toString());
        //console.log(json);
        for (var k in json.districts) {
            if (json.districts[k] instanceof Object) {
                console.log(json.districts[k].adcode);
                citycode = json.districts[k].adcode;
                return citycode;
            }
        }
    }
    catch (err) {
        console.log(err);
    }
    return "";
}

function getWeatherBase(citycode, city) {
    //查询天气
    var keyWeather = "e558bc8c234d32c87045a6178d5092d5";
    var urlWeather = "https://restapi.amap.com/v3/weather/weatherInfo?";
    urlWeather = urlWeather + "city=" + citycode + "&key=" + keyWeather + "&extensions=base";
    console.log(urlWeather);
    try {
        var res = request('GET', encodeURI(urlWeather));
        //解析天气
        console.log(res.getBody().toString());
        var json = JSON.parse(res.getBody().toString());
        //console.log(json);
        if (json.status == 1 && json.lives != null) {
            for (var k in json.lives) {
                if (json.lives[k] instanceof Object) {
                    Message = {
                        "status": "1",
                        "weather": json.lives[k].weather,
                        "temperature": json.lives[k].temperature,
                        "humidity": json.lives[k].humidity,
                        "winddirection": json.lives[k].winddirection,
                        "windpower": json.lives[k].windpower,
                        "city": city,
                        "forecasts":null
                    }
                    return Message; //JSON.stringify(Message, null, 2);
                }
            }
        }
    }
    catch (err) {
        console.log(err);
    }

    return null;
}

function getWeatherAll(citycode, city) {
    //查询天气
    var keyWeather = "e558bc8c234d32c87045a6178d5092d5";
    var urlWeather = "https://restapi.amap.com/v3/weather/weatherInfo?";
    urlWeather = urlWeather + "city=" + citycode + "&key=" + keyWeather + "&extensions=all";
    console.log(urlWeather);
    try {
        var res = request('GET', encodeURI(urlWeather));
        //解析天气
        console.log(res.getBody().toString());
        var json = JSON.parse(res.getBody().toString());
        //console.log(json);
        if (json.status == 1 && json.forecasts != null) {
            var obj = json.forecasts;
            for (var k in obj) {
                if (obj[k] instanceof Object) {
                    return obj[k].casts;//JSON.stringify(Message, null, 2);
                }
            }

        }
    }
    catch (err) {
        console.log(err);
    }

    return null;
}


http.createServer(function (request, response) {
    var IP ="";
    var Location="";
    //var IPFromRequest=request.connection.remoteAddress;

    //console.log(request.headers);
    console.log(request.headers['x-real-ip']);
    var IPFromRequest=request.headers['x-real-ip'];

    //template = /^:(ffff)?:(?!0)(?!.*\.$)((1?\d?\d|25[0-5]|2[0-4]\d)(\.|$)){4}$/
    //has_ipv4_version = template.test(ip)
    if(IPFromRequest != undefined)
    {
        var indexOfColon = IPFromRequest.lastIndexOf(':');
        IP = IPFromRequest.substring(indexOfColon+1,IPFromRequest.length); 
        console.log(IP);
        //IP = "180.158.178.227";
    }
    else
    {
        console.log("no find x-real-ip");
    }

    if(request.method == "GET")
    {
        console.log("GET mode");
        var params = url.parse(request.url, true).query;        
        if(params.location != undefined)
        {
            console.log("get:"+params.location)
            Location = params.location;
        }
    }
    if(request.method == "POST")
    {
        console.log("POST mode");
    }
     
    var City =""; //"上海市";
    var CityCode = ""; //"0210000";
   
    var result1=null;
    var result2=null;
    var message ='{"status":"0"}';
    if(IP != "")    City=getCity(IP);
    if(Location != "")    City=getCityByLL(Location);

    if (City != "") CityCode = getCitycode(City);
    if (CityCode != "") result1 = getWeatherBase(CityCode,City);
    if (CityCode != "") result2 = getWeatherAll(CityCode,City);
    if(result1 != null){
        if(result2 != null){
            result1.forecasts=result2;
        }
        message=JSON.stringify(result1, null, 2);
    }
    // 发送 HTTP 头部
    // HTTP 状态值: 200 : OK
    // 内容类型: text/plain
    response.writeHead(200, { 'Content-Type': 'text/plain;charset=UTF8' });

    // 发送响应数据
    //console.log(message);
    response.end(message);
}).listen(10100);

/*
var ret1 = getCityByLL("121.4352417,031.3792381");
console.log("Get City="+ret1)
var ret2 = getCityByLL("105.036378,27.310100");
console.log("Get City="+ret2)
*/

// 终端打印如下信息
console.log('Server running at http://127.0.0.1:10100/');
//http://maxtrix.com.cn/weather
//http://maxtrix.com.cn/weather?location=121.4352417,031.3792381
//http://maxtrix.com.cn/weather?location=105.036378,27.310100

